package logic

import (
	"context"
	"errors"
	"fmt"
	"tiktok_src/cache"
	"tiktok_src/models/mysql"

	"tiktok_src/internal/svc"
	"tiktok_src/tiktook"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *tiktook.CartAddRequest) (*tiktook.CartAddResponse, error) {
	// todo: add your logic here and delete this line
	var goods mysql.Goods
	err := goods.GoodsGetInfo()
	if err != nil {
		logx.Info("商品信息不存在", err)
		return nil, errors.New("商品信息不存在")
	}

	fmt.Println("11111111111", goods.GoodsStock)
	if goods.GoodsStock < in.GoodsNum {
		logx.Info("库存不足", err)
		return nil, errors.New("库存不足")
	}

	MapCart := map[string]interface{}{
		"UserId":     goods.UserId,
		"GoodsTitle": goods.GoodsTitle,
		"GoodsPrice": goods.GoodsPrice,
		"GoodsStock": goods.GoodsStock,
		"GoodsCover": goods.GoodsCover,
	}
	err = cache.CartAdd(in.UserId, in.GoodsId, MapCart)
	if err != nil {
		return nil, err
	}
	return &tiktook.CartAddResponse{}, nil
}
